﻿using System;
using System.Collections.Generic;
using COC.CComponent;
using COC.CEvent;
using COC.Character;
using COC.Character.Extra;
using COC.Constant;
using COC.Debug;
using COC.Internal.Handler;
using COC.Service;
using COC.Tools.AI.Motion;
using COC.UIAction;
using UnityEngine;
using System.Collections;
using Random = UnityEngine.Random;

namespace COC.CComponent
{
    public class InputEventComponent : BaseComponent
    {
        Font ArialFont;

        // Use this for initialization
        public override void OnAwake()
        {
            list.Clear();//reset input bucket
        }

        public override void OnStart()
        {
            setup();
            ArialFont = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
            StartCoroutine(actionInput());

        }

        // Update is called once per frame
        public override void OnLateUpdate()
        {
            collectInputEvent();
        }

        /// <summary>
        /// collection of input action if click or press is avaliable
        /// </summary>
        private void collectInputEvent()
        {
           
                if (Input.GetMouseButtonDown(0) && isInput)
                {
                    if (UICamera.lastHit.transform == null)//do not execute UI action
                    {
                        currMousePos = Input.mousePosition;

                        currRay = Camera.main.ScreenPointToRay(currMousePos);
                        if (Physics.Raycast(currRay, out hit, Mathf.Infinity, 1 << CommonConstants.PANEL_LAYER))
                        {
                            if (hit.collider.name == CommonConstants.MAIN_PANEL_NAME)
                            {
                                DebugTool.Log("currMousePos: " + hit.point);
                                BaseModel m = new CharacterProfile.BaseValueModel();
                                m.type = Character.Character.HERO_KING;
                                list.Enqueue(
                                    new CharacterDataModel().addBaseModel(m).addParent(_root.transform).setPosition(hit.point));
                            }
                        }
                    }
                
            }
        }

        private static SceneManager instance;
        private static CacheService _cacheService;
        private GameObject _scene;
        private static GameObject _root;
        private static Queue<CharacterDataModel> list = new Queue<CharacterDataModel>();
        private static bool isInput;
        static Vector3 currMousePos;
        static Ray currRay;
        RaycastHit hit;
        public void setup()
        {

            _cacheService = (CacheService)CEventDriven.getInstance().getService(typeof(CacheService).Name);
            _root = GameObject.FindGameObjectWithTag(CommonConstants.ROOT_TAG);


        }


        #region interaction with player


        public void setEnableInput(bool toggle)
        {
            isInput = toggle;


        }
       


        IEnumerator actionInput()
        {
            while (true)
            {
                
                if (list.Count > 0)
                {
                    instanceCharacter(list.Dequeue(), new Vector3(3, 3, 3), Quaternion.identity);
                 
                }
                yield return new WaitForSeconds(Random.Range(0, 9) / 100f + 0.05f);
            }
            
        }
        public class CharacterDataModel
        {
            public BaseModel _base;
            public Transform _parent;
            public Vector3 _pos;
            public CharacterDataModel addBaseModel(BaseModel b)
            {
                if (b != null)
                    _base = b;
                return this;
            }
            public CharacterDataModel addParent(Transform parent)
            {
                if (parent != null)
                    _parent = parent;
                return this;
            }
            public CharacterDataModel setPosition(Vector3 pos)
            {
                if (pos != null)
                    _pos = pos;
                return this;
            }
        }
        GameObject _curr;
        public void instanceCharacter(CharacterDataModel model, Vector3 scale, Quaternion rotation)
        {
            UnityEngine.Debug.Log(CEventDriven.getInstance().getService(typeof(CacheService).Name));
            _curr = null;
            string type = "";
            //find a appropriate one
            if (model._base != null)
                switch (model._base.type)
                {
                    case Character.Character.HERO_KING:
                        type = Characters.MAP_TILE;
                        _curr = findInstanceFromCache(type, model._parent, model._pos, scale, rotation);
                        if (_curr == null)
                        {
                            _curr = UnityEngine.Object.Instantiate(Resources.Load(Characters.Resource.Path.MAP_TILE)) as GameObject;
                            //_cacheService._cacheManager.prefabPool.Recycle(Characters.Component.HEALTH_BAR, _curr);
                        }
                        //add extra components
                        CharacterProfile profile = _curr.AddComponent<CharacterProfile>();
                        _curr.transform.position += Vector3.up * 5f;
                       
                        profile.enabled = false;
                        profile.setProfile(model._base.prePlaySate);
                        type = Characters.Component.HEALTH_BAR;
                        //  profile._health = findInstanceFromCache(type, _curr.transform, Vector3.zero, Vector3.zero, rotation);
                        //                        profile._health.name = _curr.name + "_extra";
                        profile._health = new GameObject("hh");
                        HUDText hUDText = profile._health.AddComponent<HUDText>();
                        // GameObject go = UnityEngine.Object.Instantiate(Resources.Load(Characters.Resource.Path.HEALTH_BAR)) as GameObject;
                        GameObject go = findInstanceFromCache(type, _curr.transform, Vector3.zero, Vector3.zero, rotation);
                        if (go == null)
                        {
                            go = UnityEngine.Object.Instantiate(Resources.Load(Characters.Resource.Path.HEALTH_BAR)) as GameObject;
                            _cacheService._cacheManager.prefabPool.Recycle(Characters.Component.HEALTH_BAR, go);
                        }
                        UnityEngine.Debug.Log("go:" + go);
                        go.transform.parent = hUDText.transform;
                        go.transform.localPosition += new Vector3(go.transform.localPosition.x - 85f, go.transform.localPosition.y + 78f, go.transform.localPosition.z);
                        go.name = "tt";
                        profile._healthUI = go;
                        hUDText.fontStyle = FontStyle.Bold;
                        hUDText.fontSize = 60;
                        hUDText.trueTypeFont = ArialFont;
                        hUDText.Add("Health", Color.magenta, 2f);
                        profile._health.AddComponent<UIFollowTarget>().target = _curr.transform;
                        profile._aiBehave = _curr.AddComponent<AIBehave>();
                        profile._aiBehave.target = GameObject.FindGameObjectWithTag(CommonConstants.PLAYER_NAME).transform;
                        profile._aiBehave.path = SceneResourceHandler.path.ToArray();
                        //profile._health = NGUITools.AddChild(HUDRoot.go, profile._health);
                        //profile._health.transform.Translate(new Vector3(1,1,1));
                        //profile._health.AddComponent<UIFollowTarget>().target=_curr.transform;

                        //profile._health.transform.position = 
                        profile.enabled = true;
                        BattleAction.IncrementInputCount();
                        break;

                }




        }


        public void predefinePrefabs()
        {
            var item = UnityEngine.Object.Instantiate(Resources.Load(Characters.Resource.Path.MAP_TILE)) as GameObject;
            var copy = UnityEngine.Object.Instantiate(Resources.Load(Characters.Resource.Path.ARCHER)) as GameObject;
            var copy2 = UnityEngine.Object.Instantiate(Resources.Load(Characters.Resource.Path.HEALTH_BAR)) as GameObject;
            putDefaultObjectTOPool(Characters.ARCHER, copy);
            putDefaultObjectTOPool(Characters.MAP_TILE, item);
            putDefaultObjectTOPool(Characters.Component.HEALTH_BAR, copy2);

        }
        private void putDefaultObjectTOPool(String type, GameObject go)
        {

            _cacheService._cacheManager.prefabPool.addPrefab(type, go.transform);

        }
        private GameObject findInstanceFromCache(string type, Transform parent, Vector3 pos, Vector3 scale, Quaternion rotation)
        {

            return _cacheService.spawnGameObject(type, parent, pos, scale, rotation);
        }
        private void rebuildCharacerValues()
        {

        }
        #endregion
    }
}